﻿#include "ScriptInstruction.h"

QHash<uchar,ScriptInstruction*(*)(char*const,int,int*)> * ScriptInstruction::fromByteArrayMap=new QHash<uchar,ScriptInstruction*(*)(char*const,int,int*)>();

ScriptInstruction::ScriptInstruction()
{

}

ScriptInstruction::ScriptInstruction(ScriptInstruction const & scriptInstruction)
{
  *this=scriptInstruction;
}

ScriptInstruction & ScriptInstruction::operator=(ScriptInstruction const & scriptInstruction)
{
  deviceId=scriptInstruction.deviceId;
  instructionFlag=scriptInstruction.instructionFlag;
  return *this;
}

ScriptInstruction::~ScriptInstruction()
{
  delete fromByteArrayMap;
}

QByteArray ScriptInstruction::toByteArray()
{
  return QByteArray(1,instructionFlag&0xff);//指令类型，1字节
}

ScriptInstruction* ScriptInstruction::fromByteArray(QByteArray data)
{
  return fromByteArray(data.data(),data.size());
}

ScriptInstruction* ScriptInstruction::fromByteArray(char * const src,int size,int * offset)
{
  int temp=0;
  if(Q_NULLPTR==offset)
    {
      offset=&temp;
    }
  if((size-*offset)<byteArraySize)
    {
      return Q_NULLPTR;
    }
  uchar type=*(src+*offset)&0xff;//得到指令类型
  *offset+=sizeof (type);//偏移量加1
  return fromByteArrayMap->contains(type)?fromByteArrayMap->value(type)(src,size,offset)->setInstructionFlag(type):
                                         Q_NULLPTR;//解析后续的数据, 在解析完毕后添加当前解析的数据
}

int ScriptInstruction::insertToFromByteArrayMap(uchar type,ScriptInstruction*(*fun)(char*const,int,int*))
{
  if( Q_NULLPTR!=fun)
    {
      fromByteArrayMap->insert(type,fun);
    }
  return 0;
}

uchar ScriptInstruction::getInstructionFlag()
{
  return instructionFlag;
}

ScriptInstruction* ScriptInstruction::setInstructionFlag(uchar instructionFlag)
{
  this->instructionFlag=instructionFlag;
  return this;
}

uint ScriptInstruction::getDeviceId()
{
  return deviceId;
}

ScriptInstruction* ScriptInstruction::setDeviceId(uint deviceId)
{
  this->deviceId=deviceId;
  return this;
}
